package org.leon.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourcesUtil {

    public static String getAbsolutePath(String path) {
        String rootPath = StaticResourcesUtil.class.getResource("/").getPath();
        return rootPath.replaceAll("\\\\", "/") + path;
    }

    public static void outputStaticResources(InputStream inputStream, OutputStream outputStream) throws IOException {

        int resourceSize = 0;
        while (resourceSize == 0) {
            resourceSize = inputStream.available();
        }

        outputStream.write(HttpProtocolUtil.httpHeader200(resourceSize).getBytes());

        long written = 0;
        int readSize = 1024;
        byte[] bytes = new byte[readSize];

        while (written < resourceSize) {
            if (written + readSize > resourceSize) {
                readSize = (int) (resourceSize - written);
                bytes = new byte[readSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();

            written += readSize;
        }
    }
}
